package com.iqiyi.pps.epg.core.utils;

/**
 * Created by karkarrotxu on 2015/7/24.
 */


import com.alibaba.fastjson.JSON;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class SendMsgUtils {
    private static final int ONE_NOTE_LENGTH = 55;
    private static Logger logger = LoggerFactory.getLogger(SendMsgUtils.class);
    private static String USER_NAME = "xuzengqiang";
    private static String USER_KEY = "pbkdf2_sha256$10000$w8Ai57uPOv4s$YOlNY3tUL3if+pK3boo78CNsSDBIri21GJ5vpXttQKQ=";
    private static String TYPE_WARN = "warn";
    private static String MOCK_FIREFOX = "Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)";
    public static String url = "http://api.msg.qiyi.domain:2800/sendMsgAll/";

    public static void sendMsg(String toList, String content, String suffix, String type) {
        try {
            String deployEnv = Configuration.getString("deploy.env");
            logger.debug("[SendMsgUtils][sendMsg] start deployEnv:" + deployEnv);
            Map<String, String> map = new HashMap<String, String>();
            map.put("username", USER_NAME);
            map.put("userkey", USER_KEY);
            map.put("tolist", toList);
            map.put("content_str", "[" + deployEnv + "]" + content);
            map.put("type", TYPE_WARN.equals(type) ? TYPE_WARN : "vip");
            suffix = new String(suffix.getBytes(), "utf-8");
            for (String key : map.keySet()) {
                map.put(key, new String(map.get(key).getBytes(), "utf-8"));
            }
            String contentStr = map.get("content_str");
            int strLength = contentStr.length();
            List<String> list = new ArrayList<String>();
            Random randInt = new Random();
            if (TYPE_WARN.equals(type) && strLength > ONE_NOTE_LENGTH) {
                int prefix = 100 + randInt.nextInt(899);
                int countByteLength = 0;
                int lastIndex = 0;
                for (int i = 0; i < strLength; i++) {
                    if (contentStr.charAt(i) > 255) {
                        countByteLength += 2;
                    } else {
                        countByteLength++;
                    }
                    if (countByteLength >= ONE_NOTE_LENGTH) {
                        appendStringToList(prefix,contentStr.substring(lastIndex, i + 1),list );
                        lastIndex = i+1;
                        countByteLength = 0;
                    }
                }
                if (lastIndex < strLength ) {
                    appendStringToList(prefix,contentStr.substring(lastIndex, strLength),list );
                }
            } else {
                list.add(contentStr);
            }
            String retValue = null;
            for (String tempData : list) {
                map.put("content", tempData + suffix);
                retValue = postContents(url, map);
                logger.debug("[SendMsgUtils][sendMsg]" + retValue);
            }
            logger.debug("[SendMsgUtils][sendMsg] end");
        } catch (UnsupportedEncodingException e) {
            logger.info("[SendMsgUtils][sendMsg] fail", e);
        }
    }

    public static void appendStringToList( int prefix,String content,List<String> list ){
        if (list.size() == 0) {
            list.add(content+ "->" + prefix);
        } else {
            list.add(prefix + "->" +content);
        }
    }

    public static String postContents(String url, Map<String, String> params) {
        HttpClientConnection connection = null;
        for (int i = 0; i < 3; i++) {
            connection = new HttpClientConnection(url, HttpClientConnection.POST_METHOD);
            connection.addReqHeader("refer", url);
            connection.addReqHeader("User-Agent", MOCK_FIREFOX);
            connection.addReqHeader("followlocation", "0");
            if (params != null) {
                connection.setReqParams(params);
            }
            connection.setSoTimeout(30000);
            connection.connect();
            logger.info("[SendMsgUtils][getMethod][url:{}][params:{}][status:{}]",
                    new Object[]{url, JSON.toJSONString(params), connection.getStatus()});
            if (connection.getStatus() == 200) {
                logger.info("[SendMsgUtils][getMethod][response:{}]", connection.getBody());
                return connection.getBody();
            }
        }
        return null;
    }

//    public static void main(String[] s) {
//        String content = "java中的String类是按照unicode进行编码的，当使用String(byte[] bytes, String encoding)构造字符串时，encoding所指的是bytes中的数据是按照那种方式编码的，而不是最后产生的String是什么编码方式，换句话说，是让系统把bytes中的数据由encoding编码方式转换成unicode编码。如果不指明，bytes的编码方式将由jdk根据操作系统决定。";
//
//        sendMsg("13391238150", content, "【epg】", "warn");
//    }
}
